package com.yq.testmodule.textalign;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.os.Build;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.text.style.ReplacementSpan;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


import com.yq.testmodule.R;

import java.lang.reflect.Field;

/**
 * Description :
 * PackageName : com.mrtrying.widget
 * Created by mrtrying on 2019/4/17 17:21.
 * e_mail : ztanzeyu@gmail.com
 */
public class ExpandableTextView extends androidx.appcompat.widget.AppCompatTextView {
    private static final String TAG = ExpandableTextView.class.getSimpleName();

    public static final String ELLIPSIS_STRING = new String(new char[]{'\u2026'});
    private static final int DEFAULT_MAX_LINE = 3;
    private static final String DEFAULT_OPEN_SUFFIX = " 查看更多";


    boolean isClosed = false;
    private int mMaxLines = DEFAULT_MAX_LINE;
    /**
     * TextView可展示宽度，包含paddingLeft和paddingRight
     */
    private int initWidth = 0;

    private SpannableStringBuilder mContentSpannableStr;


    private boolean isMoreMaxLine;//文本内容超过最大行数
    @Nullable
    private SpannableString mMoreSuffixSpan;//后缀 查看更多
    private String mMoreSuffixStr = DEFAULT_OPEN_SUFFIX;
    private int mOpenSuffixColor;



    public ExpandableTextView(Context context) {
        super(context);
        initialize();
    }

    public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    public ExpandableTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize();
    }

    /**
     * 初始化
     */
    private void initialize() {
        mOpenSuffixColor = Color.parseColor("#F23030");
        setMovementMethod(OverLinkMovementMethod.getInstance());
        setIncludeFontPadding(false);
        updateMoreSuffixSpan();

    }

    @Override
    public boolean hasOverlappingRendering() {
        return false;
    }

    public void setOriginalText(CharSequence originalText) {
        isMoreMaxLine = false;
        mContentSpannableStr = new SpannableStringBuilder();
        final int maxLines = mMaxLines;
        SpannableStringBuilder tempText = charSequenceToSpannable(originalText);


        if (maxLines != -1) {
            Layout layout = createStaticLayout(tempText);
            isMoreMaxLine = layout.getLineCount() > maxLines;

            //获取未超出最大行数的文字内容
            if(isMoreMaxLine){
                int endPos = layout.getLineEnd(maxLines - 1);
                if (originalText.length() <= endPos) {
                    mContentSpannableStr = charSequenceToSpannable(originalText);
                } else {
                    mContentSpannableStr = charSequenceToSpannable(originalText.subSequence(0, endPos));
                }
            }else {
                mContentSpannableStr = charSequenceToSpannable(originalText);
            }


            SpannableStringBuilder tempText2 = charSequenceToSpannable(mContentSpannableStr);
            if(isMoreMaxLine){
                tempText2 = tempText2.append(ELLIPSIS_STRING);
            }

            if (mMoreSuffixSpan != null) {
                tempText2.append(mMoreSuffixSpan);
            }
            //循环判断，追加查看更多后 计算一个合适的位置增加省略号"..."
            Layout tempLayout = createStaticLayout(tempText2);
            while (tempLayout.getLineCount() > maxLines) {
                int lastSpace = mContentSpannableStr.length() - 1;
                if (lastSpace == -1) {
                    break;
                }
                if (originalText.length() <= lastSpace) {
                    mContentSpannableStr = charSequenceToSpannable(originalText);
                } else {
                    mContentSpannableStr = charSequenceToSpannable(originalText.subSequence(0, lastSpace));
                }
                tempText2 = charSequenceToSpannable(mContentSpannableStr).append(ELLIPSIS_STRING);
                if (mMoreSuffixSpan != null) {
                    tempText2.append(mMoreSuffixSpan);
                }
                tempLayout = createStaticLayout(tempText2);
            }

            int lastSpace = mContentSpannableStr.length();
            if (lastSpace >= 0 && originalText.length() > lastSpace) {
                CharSequence redundantChar = originalText.subSequence(lastSpace, lastSpace + mMoreSuffixSpan.length());
                int offset = hasEnCharCount(redundantChar) - hasEnCharCount(mMoreSuffixSpan) + 1;
                lastSpace = offset <= 0 ? lastSpace : lastSpace - offset;
                mContentSpannableStr = charSequenceToSpannable(originalText.subSequence(0, lastSpace));
            }
            if(isMoreMaxLine){
                mContentSpannableStr.append(ELLIPSIS_STRING);
            }
            if (mMoreSuffixSpan != null) {
                mContentSpannableStr.append(mMoreSuffixSpan);
            }
        }
        setText(mContentSpannableStr);
        //设置监听
        super.setOnClickListener(v -> {
        });
    }

    private int hasEnCharCount(CharSequence str) {
        int count = 0;
        if (!TextUtils.isEmpty(str)) {
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c >= ' ' && c <= '~') {
                    count++;
                }
            }
        }
        return count;
    }





    /**
     * @param spannable
     * @return
     */
    private Layout createStaticLayout(SpannableStringBuilder spannable) {
        int contentWidth = initWidth - getPaddingLeft() - getPaddingRight();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StaticLayout.Builder builder = StaticLayout.Builder.obtain(spannable, 0, spannable.length(), getPaint(), contentWidth);
            builder.setAlignment(Layout.Alignment.ALIGN_NORMAL);
            builder.setIncludePad(getIncludeFontPadding());
            builder.setLineSpacing(getLineSpacingExtra(), getLineSpacingMultiplier());
            return builder.build();
        } else {
            return new StaticLayout(spannable, getPaint(), contentWidth, Layout.Alignment.ALIGN_NORMAL,
                    getLineSpacingMultiplier(), getLineSpacingExtra(), getIncludeFontPadding());
        }
    }

    private float getFloatField(String fieldName, float defaultValue) {
        float value = defaultValue;
        if (TextUtils.isEmpty(fieldName)) {
            return value;
        }
        try {
            // 获取该类的所有属性值域
            Field[] fields = this.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (TextUtils.equals(fieldName, field.getName())) {
                    value = field.getFloat(this);
                    break;
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return value;
    }


    /**
     * @param charSequence
     * @return
     */
    private SpannableStringBuilder charSequenceToSpannable(@NonNull CharSequence charSequence) {
        return new SpannableStringBuilder(charSequence);
    }

    /**
     * 初始化TextView的可展示宽度
     *
     * @param width
     */
    public void initWidth(int width) {
        initWidth = width;
    }

    @Override
    public void setMaxLines(int maxLines) {
        this.mMaxLines = maxLines;
        super.setMaxLines(maxLines);
    }

    /**
     * 设置展开后缀text
     *
     * @param openSuffix
     */
    public void setOpenSuffix(String openSuffix) {
        mMoreSuffixStr = openSuffix;
        updateMoreSuffixSpan();
    }

    /**
     * 设置展开后缀文本颜色
     *
     * @param openSuffixColor
     */
    public void setOpenSuffixColor(@ColorInt int openSuffixColor) {
        mOpenSuffixColor = openSuffixColor;
        updateMoreSuffixSpan();
    }

    /**
     * 更新 查看更多 后缀Spannable
     */
    @SuppressLint("UseCompatLoadingForDrawables")
    private void updateMoreSuffixSpan() {
        if (TextUtils.isEmpty(mMoreSuffixStr)) {
            mMoreSuffixSpan = null;
            return;
        }

        mMoreSuffixSpan = new SpannableString(mMoreSuffixStr);

        //设置字体大小 (正常14，设置11）
        mMoreSuffixSpan.setSpan(new AbsoluteSizeSpan(11, true), 0, mMoreSuffixStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置圆角背景(里面包含了图标，如果单独设置ImageSapn 背景无法包含）
        mMoreSuffixSpan.setSpan(new RoundBackgroundColorSpan(Color.parseColor("#ff0000"),
                Color.parseColor("#FFFFFF")),
                0, mMoreSuffixStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


        mMoreSuffixSpan.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Toast.makeText(getContext(), "查看更多", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(mOpenSuffixColor);
                ds.setUnderlineText(false);
            }
        }, 0, mMoreSuffixStr.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
    }


    public   class RoundBackgroundColorSpan extends ReplacementSpan {
        private int bgColor;
        private int textColor;
        public RoundBackgroundColorSpan(int bgColor, int textColor) {
            super();
            this.bgColor = bgColor;
            this.textColor = textColor;
        }
        @Override
        public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
            return ((int)paint.measureText(text, start, end));
        }

        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
            int color1 = paint.getColor();
            paint.setColor(this.bgColor);
            //绘制圆角背景
            canvas.drawRoundRect(new RectF(x, top, x + ((int) paint.measureText(text, start, end))+10, bottom), 8, 8, paint);
            paint.setColor(this.textColor);
            //将最后一个字的位置绘制成图片 所以少绘制一个字
            canvas.drawText(text, start, end-1, x, y, paint);
            paint.setColor(color1);

            //绘制图片
            Bitmap bitmap1 = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.next_white);
            RectF des = new RectF();
            int textHeight = (int) paint.getTextSize()+4;
            int left = (int) (x + ((int) paint.measureText(text, start, end-1)));
            int mTop =  (bottom +top)/2 - textHeight/2;
            des.set(left,mTop,left+textHeight,mTop+textHeight);
            canvas.drawBitmap(bitmap1,  null,des,paint);
        }
    }
}